/*******************************************
 * Copyright 2007 Aphrodite Framework for javaME .
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the GNU Public License v2.0
 * which accompanies this distribution, and is available at
 * http://www.gnu.org/licenses/old-licenses/gpl-2.0.html
 * Email : owner@aphroditeme.dev.java.net
 * Contributors:
 *     Kent Elton - initial API and implementation
 *******************************************/

package com.aphrodite.ui.widgets;

import javax.microedition.lcdui.Graphics;
import javax.microedition.lcdui.Image;

/**
 * Use as image as a progress bar. By default the percent is 0, you need to set
 * the percentage to see the widget.
 * 
 * @author kentelt
 * 
 */
public class ImageProgress extends Widget {

	private int clipAmt = 0;
	private Image image;
	private int layout = LAYOUT_HORIZONTAL;
	private int percent;

	public ImageProgress(Theme theme, Image image) {
		this(theme, image, 1, 1, LAYOUT_HORIZONTAL);
	}

	public ImageProgress(Theme theme, Image image, int x, int y, int layout) {
		super(theme, image.getWidth(), image.getHeight());
		this.layout = layout;
		this.image = image;
		updateModel();
	}

	public void cleanUp() {
		image = null;
	}

	public int getLayout() {
		return this.layout;
	}

	public int getPercent() {
		return percent;
	}

	public void render(Graphics g) {
		if (!isVisible)
			return;

		capture(g, width, height, false);
		if (layout == LAYOUT_HORIZONTAL) {
			g.setClip(0, 0, clipAmt, height);
		} else {
			g.setClip(0, 0, width, clipAmt);

		}
		g.drawImage(image, 0, 0, 0);
		g.setClip(0, 0, width, height);
		release(g, width, height, false);

	}

	public void setImage(Image image) {
		this.image = image;
		updateModel();
	}

	public void setLayout(int layout) {
		if (layout == LAYOUT_HORIZONTAL || layout == LAYOUT_VERTICAL) {
			if (this.layout == LAYOUT_VERTICAL)// rotate the image back if its
			// already vertical
			{
				this.image = com.aphrodite.image.ImageTransformation.rotateSimple(this.image, 270);
			}
			this.layout = layout;
			updateModel();
			setPercent(percent);
			reDraw();
		} else {
			throw new IllegalArgumentException("Invalid layout value");
		}
	}

	public void setPercent(int percent) {
		if (percent > 100) {
			throw new IllegalArgumentException("Invalid percentage");
		}
		this.percent = percent;
		clipAmt = (((layout == LAYOUT_VERTICAL) ? height : width) * percent) / 100;
		reDrawWidget();
	}

	protected void updateModel() {
		if (this.layout == LAYOUT_VERTICAL) {
			this.image = com.aphrodite.image.ImageTransformation.rotateSimple(this.image, 90);
		}
		this.width = this.image.getWidth();
		this.height = this.image.getHeight();
		sizeChanged(width, height);

	}

}
